<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>Code blocks adorn - Layui</title>
  <link href="css/layui.css" rel="stylesheet">
  <style>
    pre{margin: 16px 0;}
  </style>
</head>
<body class="layui-padding-5">

<pre id="test" class="test123" lay-skin="notepad" >

from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import List
import yaml
from prance import ResolvingParser
from jsonpath_ng import parse
from fastapi_offline import FastAPIOffline

app = FastAPIOffline()

#app = FastAPI()

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

class Endpoint(BaseModel):
    endpointName: str
    endpointId: str
    ip: str
    port: int
    type: int

class Link(BaseModel):
    linkId: str
    linkName: str
    level: str
    protected: int
    endpoints: List[Endpoint]

links_db = []

@app.post("/links", response_model=Link, status_code=201)
async def create_link(link: Link):
    links_db.append(link)
    return link

@app.get("/links", response_model=List[Link])
async def get_links():
    return links_db

@app.get("/links", response_model=Link)
async def get_link(linkId: str):
    link = next((link for link in links_db if link.linkId == linkId), None)
    if link is None:
        raise HTTPException(status_code=404, detail="Link not found")
    return link

@app.delete("/links", status_code=204)
async def delete_link(linkId: str):
    global links_db
    links_db = [link for link in links_db if link.linkId != linkId]
    if not any(link.linkId == linkId for link in links_db):
        raise HTTPException(status_code=404, detail="Link not found")
    return None



def generate_routes(app, spec):
    for path, path_item in spec['paths'].items():
        for method, operation in path_item.items():
            if method in ['get', 'post', 'put', 'delete']:
                operation_id = operation['operationId']
                app.add_api_route(path, lambda: {}, methods=[method.upper()], name=operation_id)

# 不需要动态加载路径
#spec = load_openapi_spec('openapi.yaml')
#generate_routes(app, spec)


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=12345)

</pre>



<!-- 第三方语法高亮库 -->
<script src="js/highlight.min.js"></script>
<script src="js/prism.min.js"></script>

<!-- layui -->
<script src="layui.js"></script>
<script>
layui.use(['code', 'dropdown'], function(){
  var dropdown = layui.dropdown;
  var $ = layui.$;

  // return;

  // 高亮主题 css 库
  var themeData = $.map([
    // hljs 主题库
    'css/monokai-sublime.min.css',
    'https://cdn.staticfile.org/highlight.js/11.8.0/styles/vs2015.min.css',
    'https://cdn.staticfile.org/highlight.js/11.8.0/styles/vs.min.css',
    'https://cdn.staticfile.org/highlight.js/11.8.0/styles/github-dark.min.css',
    'https://cdn.staticfile.org/highlight.js/11.8.0/styles/github.min.css',
    'https://cdn.staticfile.org/highlight.js/11.8.0/styles/base16/google-dark.min.css',
    'https://cdn.staticfile.org/highlight.js/11.8.0/styles/base16/google-light.min.css',

    '-',
    // prism 主题库
    'https://cdn.staticfile.org/prism/1.29.0/themes/prism-dark.min.css',
    'https://cdn.staticfile.org/prism/1.29.0/themes/prism.min.css'
  ], function(v, index) {
    return {
      title: v,
      link: v,
      highlighter: v.indexOf('prism') === -1 ? 'hljs' : 'prism',
      type: v === '-' ? '-' : 'normal'
    };
  });

  var codeInst = layui.code({
    elem: '#test',
    preview: true,
    codeStyle: 'height: 510px;font-size: 14px;',
    previewStyle: 'word-wrap: break-word;',
    wordWrap: true, // 是否自动换行
    lang: 'python',
    highlighter: "hljs",
    codeRender: function (code, opts) { // 初始高亮
      layui.link(themeData[1].link, 'layui-code-theme');
      return hljs.highlight(code, {language: opts.lang}).value;
    },
    tools: [
      'full',
      {
        title: ['文字换行'],
        type: 'form',
        event: function(obj) {
          dropdown.render({
            elem: obj.elem,
            data: [{title: '自动换行', wordWrap: true}, {title: '不自动换行', wordWrap: false}],
            show: true,
            click: function(data, othis) {
              codeInst.reload({
                wordWrap: data.wordWrap
              });
            }
          });
        }
      },
      {
        title: ['切换高亮主题'],
        type: 'theme',
        event: function(obj) {
          dropdown.render({
            elem: obj.elem,
            data: themeData,
            show: true,
            click: function(data, othis) {
              $('#layuicss-layui-code-theme').remove();
              layui.link(data.link, 'layui-code-theme');

              // 若高亮器有变化，则重载
              if (data.highlighter !== codeInst.config.highlighter) {
                var highlighter = {
                  hljs: function(code, opts) {
                    return hljs.highlight(code, {
                      language: opts.lang
                    }).value;
                  },
                  prism: function(code, opts) {
                    return Prism.highlight(
                      code,
                      Prism.languages[opts.lang],
                      opts.lang
                    );
                  }
                };
                // 重载
                codeInst.reload({
                  highlighter: data.highlighter,
                  codeRender: function (code, opts) {
                    return highlighter[data.highlighter](code, opts);
                  }
                });
              }
            }
          });
        }
      }
    ]
  });

  // 语法高亮重载
  codeInst.reloadCode({
    codeRender: function(code, opts) {
      layui.link(themeData[1].link, 'layui-code-theme');
      return hljs.highlight(code, {language: opts.lang}).value;
    }
  });


  // 通用实例，根据元素属性定制化参数
  layui.code({
    elem: '.layui-code',
    tools: ['tips'],
    langMarker: true,
    lang: 'python',
    preview: false
  });
});
</script>
</body>
</html>
